package com.situ.crm.interceptor;

import com.situ.crm.pojo.entity.User;
import com.situ.crm.util.PermissionUtils;
import com.situ.crm.util.UserContext;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object target) throws Exception {
        User user = (User) request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        if (user != null) {
            // 用户虽然已经登录，但是还要查看用户有没有访问的权限
            // 如果返回为true,表示用户拥有这个权限访问该方法或者该方法不受权限控制,直接放行
            // 如果为false,拦截该请求
            String servletPath = request.getServletPath();
            if (PermissionUtils.checkPermission(servletPath)) {
                return  true;// 有权限，放行
            } else {
                //获取拦截目标的类型和方法
                HandlerMethod hadler = (HandlerMethod) target;
                // 如果请求的内容是页面的话,跳转到nopermissions.jsp页面,
                // 如果请求的是Ajax数据的话,跳转到nopermissions.json
                if (hadler.getMethod().isAnnotationPresent(ResponseBody.class)) {
                    response.sendRedirect("/nopermission.json");
                } else {
                    response.sendRedirect("/nopermission.jsp");
                }
                System.out.println(request.getRequestURI());
                return false;
            }
        } else{
            response.sendRedirect(request.getContextPath() + "/user/getLoginPage");
            return  false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
